import axios from "axios";
import Storage from '../utils/storage'
import qs from 'qs'
import router from "../router";
import { showToast } from '@/utils/comm';
// import { useRouter } from "vue-router";
import { Toast } from 'vant';

// const router = useRouter()
// 获取域名
import baseUrl from './config'



//延迟加载类  loading.open() 启用  loading.close() 关闭
const loading = {
    loadingInstance: null,
    timer: 0,//网络延迟时 才显示加载中
    open: function () {
        if (this.timer) {
            return;
        }
        this.timer = setTimeout(() => {
            this._load();
        }, 500)
    },
    close: function () {
        if (this.timer) {
            clearTimeout(this.timer)
            this.timer = false;
        }
        if (this.loadingInstance !== null) {
            Toast.clear
            
        }
        this.loadingInstance = null
    },
    _load: function () {
        if (this.loadingInstance == null) {
            this.loadingInstance = Toast.loading({
                message: '加载中...',
                forbidClick: true,
              });
        }
    },
}

const request = (config)=>{
    const instance = axios.create({
        baseURL:baseUrl,
        timeout:5000,
        headers:config?.headers || {
            'X-Requested-With': 'foobar',
            "Content-Type": "application/x-www-form-urlencoded",
        }
    })
    console.log(baseUrl,'---baseUrl')
    //请求拦截器
    instance.interceptors.request.use(config=>{
        loading.open()
        console.log(config,'--请求')
        config.headers['token'] = Storage.get('token') || ''
        if(config.method ==='post'){
            if (config.headers['Content-Type'] !== 'application/json') {
                config.data = qs.stringify(config.data);
            }
        }
        return config
    },error=>{
        console.log(error,'---请求错误')
        return Promise.reject(error)
    })

    //响应拦截器
    instance.interceptors.response.use(response=>{
        loading.close();
        const code = response.data.code
        if(code==1){
            return response.data
        }else{
            showToast(response.data.msg)
            //如果请求配置中注明需要返回上一页
            if(config.option?.isBack==1){
                setTimeout(()=>{
                    router.back()
                },1500)
            }else if(config.option?.reject ==1){
                //如果错误需要抛回处理
                return Promise.reject(response.data);
            }else if(code==401){
                //请登录
                router.replace({
                    path:'/login'
                })
            }
        }
    })

    //发送请求
    return instance(config)
}
export default request;